package com.itheima.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component//需要交给IOC容器管理
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override//目标资源方法运行之前运行
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        //获取请求url
        String url = req.getRequestURI();
        log.info(""+url);
        //判断请求是否包含login，如果包含，说明是登陆操作，放行
        if (url.contains("login")){
            log.info("登录操作");
            return true;
        }
        //获取请求头中的令牌
        String jwt = req.getHeader("token");
        if (!StringUtils.hasLength(jwt)){
            log.info("");
            Result error = Result.error("NOT LOGIN");
            //手动转换对象JSON格式
            String notLogin = JSONObject.toJSONString(error);
            //返回
            resp.getWriter().write(notLogin);
            return false;
        }
        //解析token，如果解析失败，返回错误信息（未登录）快捷键alt+ctrl+t
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {//jwt解析失败
            e.printStackTrace();
            log.info("解析令牌失败，返回一个错误信息");
            Result error = Result.error("NOT LOGIN");
            //手动转换对象JSON格式
            String notLogin = JSONObject.toJSONString(error);
            //返回
            resp.getWriter().write(notLogin);
            return false;
        }

        //放行
        log.info("令牌合法，放行");
        return true;
    }

    @Override//目标资源方法运行之后运行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override//视图渲染完毕后运行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
